package pl.edu.pk.adcampaignfacebook.interfaces.integration;

import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.map.ObjectMapper;

import pl.edu.pk.adcampaignfacebook.core.AuthRequest;
import pl.edu.pk.adcampaignfacebook.dto.PhotoComment;
import pl.edu.pk.adcampaignfacebook.dto.PhotoService;
import pl.edu.pk.adcampaignfacebook.dto.UserDTO;
import pl.edu.pk.adcampaignfacebook.dto.UserService;
import pl.edu.pk.adcampaignfacebook.interfaces.SocialService;
import pl.edu.pk.adcampaignfacebook.rest.responses.CommentResponse;
import pl.edu.pk.adcampaignfacebook.rest.responses.LoginResponse;
import pl.edu.pk.adcampaignfacebook.rest.responses.PhotoResponse;
import pl.edu.pk.adcampaignfacebook.rest.responses.RestComment;
import pl.edu.pk.adcampaignfacebook.rest.responses.StatusCodes;


public class IntegrationAPI implements SocialService {
	
	private static final String NAME = "IntegrationAPI";
	private static final String LOGINURL = "/integration";

	private UserService userService;
	private String token;
	
	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public AuthRequest getAuthRequest(UserDTO user) {
		AuthRequest ar = new AuthRequest();
		ar.setUserId(user.getId());
		ar.setUrl(LOGINURL+"?state="+NAME+user.getId());
		ar.setState(NAME+user.getId());
		ar.setService(NAME);
		return ar;
	}

	@Override
	public UserService getAuthUser(AuthRequest authReq, String code) {
		UserService us = new UserService();
		String[] data = code.split(",");
		
		us.setName(data[0]);  			//Displayed Name
		us.setIdOnService(data[1]);		//Login
		us.setSecretToken(data[2]);		//Password
		us.setToken(data[3]);			//URL
		
		us.setServiceName(NAME);
		us.setUserId(authReq.getUserId());
		return us;
	}

	@Override
	public PhotoService addPhoto(String url, String title, String description) {
		
		try {
			
			ObjectMapper maper = new ObjectMapper();
			List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		    qparams.add(new BasicNameValuePair("token", token));
		    qparams.add(new BasicNameValuePair("url", url));
		    qparams.add(new BasicNameValuePair("title", title));
		    qparams.add(new BasicNameValuePair("description", description));
		
		    URI uri = URIUtils.createURI(null, userService.getToken(), -1, "/addPhoto",
			        URLEncodedUtils.format(qparams, "UTF-8"), null);
			
			PhotoResponse presp = maper.readValue(uri.toURL(), PhotoResponse.class);
			if(presp.getStatus() == StatusCodes.OK){
				PhotoService ps = new PhotoService();
				ps.setIdOnService(presp.getMessage_id());
				ps.setTimestamp(new Date());
				
				ps.setTitle(title);
				ps.setUserServiceId(userService.getId());
				ps.setDirectLink(url);
				return ps;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public PhotoComment addComent(PhotoService photoService, String comment) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<PhotoComment> getComments(PhotoService photoService, Date date) {
		try {
			ObjectMapper maper = new ObjectMapper();
	
			List<NameValuePair> qparams = new ArrayList<NameValuePair>();
			qparams.add(new BasicNameValuePair("token", token));
		    qparams.add(new BasicNameValuePair("message_id", photoService.getIdOnService()));
		
			URI uri = URIUtils.createURI(null, userService.getToken(), -1, "/getComments",
			        URLEncodedUtils.format(qparams, "UTF-8"), null);
			
			CommentResponse cresp = maper.readValue(uri.toURL(), CommentResponse.class);
			if(cresp.getStatus() == StatusCodes.OK){
				List<RestComment> rlist= cresp.getComments();
				List<PhotoComment> clist = new ArrayList<PhotoComment>();
				for(RestComment rc : rlist){
					PhotoComment pc = new PhotoComment();
					pc.setAuthorName(rc.getAuthor());
					pc.setText(rc.getText());
					pc.setPictureServiceId(photoService.getId());
					pc.setUserServiceId(photoService.getUserServiceId());
					clist.add(pc);
				}
				return clist;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<PhotoService> getRecentlyUpdatedPhotos(Date date) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setContext(UserService user) {
		userService = user;
		try {
			ObjectMapper maper = new ObjectMapper();
	
			List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		    qparams.add(new BasicNameValuePair("login", userService.getIdOnService()));
		    qparams.add(new BasicNameValuePair("password", userService.getSecretToken()));
		
			URI uri = URIUtils.createURI(null, userService.getToken(), -1, "/login",
			        URLEncodedUtils.format(qparams, "UTF-8"), null);
			
			LoginResponse lresp = maper.readValue(uri.toURL(), LoginResponse.class);
			if(lresp.getStatus() == StatusCodes.OK){
				token = lresp.getToken();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean deletePhoto(PhotoService photoToDelete) {
		// TODO Auto-generated method stub
		return false;
	}
	
	public String getToken(){
		return this.token;
	}

}
